package com.atguigu.tingshu.common.util;

/**
 * 获取当前用户信息帮助类
 */
public class AuthContextHolder {

    private static ThreadLocal<Long> userId = new ThreadLocal<Long>();


    public static void main(String[] args) {
        //在一个线程中，调用ThreadLocal对象中set方法存数据
        new Thread(() -> {
            userId.set(1L);
            System.out.println(Thread.currentThread().getName() + ":,获取到ThreadLocal中数据：" + userId.get());
        }, "A").start();

        new Thread(() -> {
            userId.set(2L);
            System.out.println(Thread.currentThread().getName() + ":,获取到ThreadLocal中数据：" + userId.get());
        }, "B").start();
    }


    private static ThreadLocal<String> username = new ThreadLocal<String>();

    public static void setUserId(Long _userId) {
        userId.set(_userId);
    }

    public static Long getUserId() {
        //实现登录后，动态从ThreadLocal中获取，前提存入ThreadLocal
        return userId.get();
        //未实现登录功能前固定返回：1
        //return 1L;
    }

    public static void removeUserId() {
        userId.remove();
    }

    public static void setUsername(String _username) {
        username.set(_username);
    }

    public static String getUsername() {
        return username.get();
    }

    public static void removeUsername() {
        username.remove();
    }

}
